﻿using CMS_Tools.GeoNames;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace CMS_Tools.Forms
{
    public partial class frmGeoNames : Form
    {
        public frmGeoNames()
        {
            InitializeComponent();
        }

        private void btn_loadData_Click(object sender, EventArgs e)
        {
            btn_loadData.Enabled = false;
            int id;
            try
            {
                id = int.Parse(this.txt_GeoNameID.Text);
            }
            catch
            {
                return;
            }
            GeonameData g = GeoNamesOrgWebservice.Get(id);

            this.treeViewGeoNameData.Nodes.Clear();

            TreeNode earthTreeNode = CreateTreeNode(g);
            var hier = g.Children(GeoNamesDataStyle.Full);



            foreach (GeonameData geoname in hier) {
                TreeNode areaNode = CreateTreeNode(geoname);

                //var countries = geoname.Children(GeoNamesDataStyle.Full);
                //foreach (GeonameData countryData in countries)
                //{
                //    TreeNode countryDataNode = CreateTreeNode(countryData);

                //    var cities = countryData.Children(GeoNamesDataStyle.Full);
                //    foreach (GeonameData cityData in cities)
                //    {
                //        TreeNode cityDataNode = CreateTreeNode(cityData);
                //        countryDataNode.Nodes.Add(cityDataNode);
                        
                //    }

                //    areaNode.Nodes.Add(countryDataNode);
                    
                //}

                earthTreeNode.Nodes.Add(areaNode);
            }
                


            this.treeViewGeoNameData.Nodes.Add(earthTreeNode);
            btn_loadData.Enabled = true;
        }

        private TreeNode CreateTreeNode(GeonameData geoname)
        {
            string str = string.Format("{0} ({1}, {2})", geoname.Name, geoname.Fcl, geoname.Fcode);

            TreeNode n = new TreeNode(str);
            n.Tag = geoname;
            return n;
        }

        private void btn_loadNodeChildren_Click(object sender, EventArgs e)
        {
            if (this.treeViewGeoNameData.SelectedNode == null)
                return;
            GeonameData x = this.treeViewGeoNameData.SelectedNode.Tag as GeonameData;
            if (x == null)
                return;

            var hier = x.Children(GeoNamesDataStyle.Full);
            this.treeViewGeoNameData.SelectedNode.Nodes.Clear();

            foreach (GeonameData geoname in hier)
                this.treeViewGeoNameData.SelectedNode.Nodes.Add(CreateTreeNode(geoname));

            this.treeViewGeoNameData.SelectedNode.Expand();
        }

        private void treeViewGeoNameData_AfterSelect(object sender, TreeViewEventArgs e)
        {


            if (this.treeViewGeoNameData.SelectedNode == null)
                return;

            this.propertyGrid_NodeData.SelectedObject = this.treeViewGeoNameData.SelectedNode.Tag;

            // this.btnGetHierarchy.Enabled = this.treeViewGeoNameData.SelectedNode.Tag is GeonameData;
            // this.btnGetChildren.Enabled = this.treeViewGeoNameData.SelectedNode.Tag is GeonameData;

            GeonameData x = this.treeViewGeoNameData.SelectedNode.Tag as GeonameData;
            if (x == null)
                return;
            //this.listView1.Items.Clear();
            //foreach (AlternateName name in x.AlternateNames())
            //    this.listView1.Items.Add(new ListViewItem(name.ToString()));

            this.txt_Latitude.Text = x.Latitude.ToString();
            this.txt_Longitude.Text = x.Longitude.ToString();


        }






        private void btnCreateFiles_Click(object sender, EventArgs e)
        {
            List<GeonameData> allContinents = GeoNamesOrgWebservice.Get(6295630).Children().ToList();
            List<GeonameData> allCountries = new List<GeonameData>();

            foreach (var continent in allContinents)
            {
                allCountries.AddRange(continent.Children().ToList());
            }


            allCountries = allCountries.OrderBy(c => c.Name).ToList();

            using (XmlWriter writer = XmlWriter.Create(@"D:\DevApps\test.xml"))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("Countries");
                
                foreach (GeonameData country in allCountries)
                {
                    writer.WriteStartElement("Country");

                    writer.WriteElementString("Name", country.CountryName);
                    writer.WriteElementString("LocalizedName", country.ArabicName);
                    writer.WriteElementString("TwoLetterIsoCode", country.CountryCode);
                    writer.WriteElementString("ThreeLetterIsoCode", country.CountryCode);
                    writer.WriteElementString("NumericIsoCode", "0");
                    writer.WriteElementString("Published", "1");

                    writer.WriteElementString("Latitude", country.Latitude.ToString("G"));
                    writer.WriteElementString("Longitude", country.Longitude.ToString("G"));

                    writer.WriteElementString("Fcl", country.Fcl);
                    writer.WriteElementString("Fcode", country.Fcode);
                    writer.WriteElementString("FclName", country.FclName);
                    writer.WriteElementString("FcodeName", country.FcodeName);

                    writer.WriteElementString("Population", country.Population.ToString());

                    writer.WriteElementString("GeoNamesID", country.Id.ToString());


                    writer.WriteStartElement("Cities");
                    foreach (var city in country.Children())
                    {
                        writer.WriteStartElement("City");

                        writer.WriteElementString("Name", city.Name);
                        writer.WriteElementString("LocalizedName", city.ArabicName);

                        writer.WriteElementString("Published", "1");
                        writer.WriteElementString("Abbreviation", city.CityAbbreviation);

                        writer.WriteElementString("Latitude", city.Latitude.ToString("G"));
                        writer.WriteElementString("Longitude", city.Longitude.ToString("G"));

                        writer.WriteElementString("Fcl", city.Fcl);
                        writer.WriteElementString("Fcode", city.Fcode);
                        writer.WriteElementString("FclName", city.FclName);
                        writer.WriteElementString("FcodeName", city.FcodeName);

                        writer.WriteElementString("Population", city.Population.ToString());

                        writer.WriteElementString("GeoNamesID", city.Id.ToString());
                        writer.WriteElementString("UTCOffset", city.TimezoneOffsetGmt.ToString());
                        writer.WriteEndElement();
                    }
                    writer.WriteEndElement();

                    writer.WriteEndElement();
                }

                writer.WriteEndElement();
                writer.WriteEndDocument();
            }


            MessageBox.Show("Finished");

        }

        private void btnGetAllFiles_Click(object sender, EventArgs e)
        {
            string parentDir = @"D:\DevApps\ITCMS\GeoNamesFiles\";
            string dir = parentDir;

            DirectoryInfo di = new DirectoryInfo(dir);
            if (!di.Exists)
                di.Create();

            var earth = GeoNamesOrgWebservice.Get(6295630);

            //Details
            var earthDetailsDoc = GeoNamesOrgWebservice.GetDetailsXmlDoc(6295630);
            earthDetailsDoc.Save(dir + @"\earth_details.xml");
            //Children
            var earthChildDoc = GeoNamesOrgWebservice.GetChildrenXmlDoc(6295630, GeoNamesDataStyle.Full);
            earthChildDoc.Save(dir + @"\earth_children.xml");
            //Continents folder
            dir = parentDir + @"Continents\";
            di = new DirectoryInfo(dir);
            if (!di.Exists)
                di.Create();


            foreach (var continent in earth.Children())
            {
                dir = parentDir + @"Continents\" + continent.Name + @"\";
                di = new DirectoryInfo(dir);
                if (!di.Exists)
                    di.Create();

                //Details
                var continentDetailsDoc = GeoNamesOrgWebservice.GetDetailsXmlDoc(continent.Id);
                continentDetailsDoc.Save(dir + continent.Name + "_details.xml");
                //Children
                var continentChildDoc = GeoNamesOrgWebservice.GetChildrenXmlDoc(continent.Id, GeoNamesDataStyle.Full);
                continentChildDoc.Save(dir + continent.Name + "_children.xml");
                //Countries folder
                dir = parentDir + @"Continents\" + continent.Name + @"\" + @"Countries\";
                di = new DirectoryInfo(dir);
                if (!di.Exists)
                    di.Create();


                foreach (var country in continent.Children())
                {
                    dir = parentDir + @"Continents\" + continent.Name + @"\" + @"Countries\" + country.Name + @"\";
                    di = new DirectoryInfo(dir);
                    if (!di.Exists)
                        di.Create();

                    //Details
                    var countryDetailsDoc = GeoNamesOrgWebservice.GetDetailsXmlDoc(country.Id);
                    countryDetailsDoc.Save(dir + country.Name + "_details.xml");
                    //Children
                    var countryChildDoc = GeoNamesOrgWebservice.GetChildrenXmlDoc(country.Id, GeoNamesDataStyle.Full);
                    countryChildDoc.Save(dir + country.Name + "_children.xml");
                    //Cities folder
                    dir = parentDir + @"Continents\" + continent.Name + @"\" + @"Countries\" + country.Name + @"\" + @"Cities\";
                    di = new DirectoryInfo(dir);
                    if (!di.Exists)
                        di.Create();
                    
                    foreach (var city in country.Children())
                    {
                        dir = parentDir + @"Continents\" + continent.Name + @"\" + @"Countries\" + country.Name + @"\" + @"Cities\" + city.Name + @"\";
                        di = new DirectoryInfo(dir);
                        if (!di.Exists)
                            di.Create();

                        //Details
                        var cityDetailsDoc = GeoNamesOrgWebservice.GetDetailsXmlDoc(city.Id);
                        cityDetailsDoc.Save(dir + city.Name + "_details.xml");
                        //Children
                        var cityChildDoc = GeoNamesOrgWebservice.GetChildrenXmlDoc(city.Id, GeoNamesDataStyle.Full);
                        cityChildDoc.Save(dir + city.Name + "_children.xml");
                        //Cities folder
                        dir = parentDir + @"Continents\" + continent.Name + @"\" + @"Countries\" + country.Name + @"\" + @"Cities\" + city.Name + @"\" + @"Cities\";
                        di = new DirectoryInfo(dir);
                        if (!di.Exists)
                            di.Create();


                        foreach (var subCity in city.Children())
                        {
                            //Details
                            var subCityDetailsDoc = GeoNamesOrgWebservice.GetDetailsXmlDoc(subCity.Id);
                            subCityDetailsDoc.Save(dir + subCity.Name + "_details.xml");
                            //Children
                            var subCityChildDoc = GeoNamesOrgWebservice.GetChildrenXmlDoc(subCity.Id, GeoNamesDataStyle.Full);
                            subCityChildDoc.Save(dir + subCity.Name + "_children.xml");
                            
                        }

                    }
                }
            }

            MessageBox.Show("Finished");
        }


    }
}
